<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.nickName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" value="1" />
            <el-option label="审核通过" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
        </div>
      </template>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" :index="indexMethod" />
        <el-table-column prop="nickName" label="姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="isDriver" label="是否为司机" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isDriver === 2 ? 'success' : 'info'">
              {{ row.isDriver === 2 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="carNumber" label="车牌号" />
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusType(row.auditStatus)">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.auditStatus !== 1"
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="row.auditStatus === 1"
              type="success" 
              size="small" 
              @click="handleApprove(row)"
            >
              通过审核
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="600px"
      @close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="editForm.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="editForm.password" 
            type="password" 
            placeholder="输密码就修改,不输不改" 
          />
        </el-form-item>
        <el-form-item label="角色" prop="permissionId">
          <el-select v-model="editForm.permissionId" placeholder="请选择角色" style="width: 100%">
            <el-option 
              v-for="role in roleOptions" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否司机" prop="isDriver">
          <el-radio-group v-model="editForm.isDriver">
            <el-radio :value="1">不是驾驶员</el-radio>
            <el-radio :value="2">我是驾驶员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车牌号" prop="carNumber" v-if="editForm.isDriver === 2">
          <el-input v-model="editForm.carNumber" placeholder="请输入车牌号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 通过审核对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="通过审核"
      width="500px"
    >
      <el-form
        ref="approveFormRef"
        :model="approveForm"
        :rules="approveRules"
        label-width="100px"
      >
        <div style="text-align: center; padding: 20px 0;">
          <p>确定要通过审核用户 <strong>{{ currentUser?.nickName }}</strong> 吗？</p>
          <p style="color: #666; font-size: 14px;">手机号：{{ currentUser?.phone }}</p>
        </div>
        <el-form-item label="选择角色" prop="roleId">
          <el-select v-model="approveForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option 
              v-for="role in roleOptions" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, 
  deleteUser,
  updateUser,
  approveUser
} from '@/api/user'
import { getRoleList } from '@/api/role'

// 搜索表单
const searchForm = reactive({
  nickName: '',
  auditStatus: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref()
const roleOptions = ref([])

// 编辑表单
const editForm = reactive({
  id: '',
  nickName: '',
  phone: '',
  password: '',
  permissionId: '',
  isDriver: 1,
  carNumber: ''
})

// 编辑表单验证规则
const editRules = {
  nickName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  permissionId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  isDriver: [
    { required: true, message: '请选择是否为司机', trigger: 'change' }
  ],
  carNumber: [
    { 
      required: true, 
      message: '请输入车牌号', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (editForm.isDriver === 2 && !value) {
          callback(new Error('请输入车牌号'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 通过审核对话框
const approveDialogVisible = ref(false)
const currentUser = ref(null)
const approveFormRef = ref()

// 通过审核表单
const approveForm = reactive({
  roleId: ''
})

// 通过审核表单验证规则
const approveRules = {
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 用户表单
const userForm = reactive({
  id: '',
  nickName: '',
  phone: '',
  isDriver: 1,
  carNumber: '',
  auditStatus: 1,
  password: ''
})

// 表单验证规则
const userRules = {
  nickName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  isDriver: [
    { required: true, message: '请选择是否为司机', trigger: 'change' }
  ],
  carNumber: [
    { 
      required: true, 
      message: '请输入车牌号', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (userForm.isDriver === 2 && !value) {
          callback(new Error('请输入车牌号'))
        } else {
          callback()
        }
      }
    }
  ],
  auditStatus: [
    { required: true, message: '请选择审核状态', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 序号计算方法
const indexMethod = (index) => {
  return (pagination.current - 1) * pagination.size + index + 1
}

// 获取审核状态类型
const getAuditStatusType = (status) => {
  switch (status) {
    case 1: return 'warning'
    case 2: return 'success'
    case 3: return 'danger'
    default: return 'info'
  }
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  switch (status) {
    case 1: return '待审核'
    case 2: return '审核通过'
    case 3: return '审核不通过'
    default: return '未知'
  }
}

// 获取用户列表
const getUserData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    const response = await getUserList(params)
    tableData.value = response.records || response.data || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getUserData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    nickName: '',
    auditStatus: ''
  })
  handleSearch()
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    getUserData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 编辑用户
const handleEdit = (row) => {
  console.log('编辑用户数据:', row)
  console.log('当前角色选项:', roleOptions.value)
  editForm.id = row.id
  editForm.nickName = row.nickName
  editForm.phone = row.phone
  editForm.permissionId = row.permissionId
  editForm.isDriver = row.isDriver
  editForm.carNumber = row.carNumber
  editForm.password = '' // 编辑时密码不显示
  editDialogVisible.value = true
}

// 编辑对话框关闭
const handleEditDialogClose = () => {
  editFormRef.value.resetFields()
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    
    // 如果密码为空，则不传递密码字段
    const submitData = { ...editForm }
    if (!submitData.password) {
      delete submitData.password
    }
    
    console.log('提交的编辑数据:', submitData)
    await updateUser(submitData)
    ElMessage.success('编辑成功')
    editDialogVisible.value = false
    getUserData()
  } catch (error) {
    console.error('编辑失败:', error)
    ElMessage.error('编辑失败')
  }
}

// 通过审核
const handleApprove = (row) => {
  currentUser.value = row
  approveForm.roleId = '' // 重置角色选择
  approveDialogVisible.value = true
}

// 提交通过审核
const handleApproveSubmit = async () => {
  try {
    await approveFormRef.value.validate()
    
    // 调用审核通过接口
    const auditData = {
      id: currentUser.value.id,
      permissionId: approveForm.roleId
    }
    
    console.log('通过审核数据:', auditData)
    await approveUser(auditData)
    
    ElMessage.success('审核通过成功')
    approveDialogVisible.value = false
    getUserData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  getUserData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getUserData()
}

// 获取角色列表
const getRoleData = async () => {
  try {
    const response = await getRoleList()
    console.log('角色列表响应:', response)
    // 提取分页数据中的records数组
    roleOptions.value = response?.records || response || []
    console.log('角色选项:', roleOptions.value)
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 初始化
onMounted(() => {
  getUserData()
  getRoleData()
})
</script>

<style lang="scss" scoped>
.user-management {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  // 表格数据居中样式
  :deep(.el-table) {
    .el-table__cell {
      text-align: center !important;
    }
    
    .el-table__header {
      .el-table__cell {
        text-align: center !important;
      }
    }
  }
  
  // 表单居中样式
  :deep(.el-dialog) {
    .el-form {
      text-align: center;
      
      .el-form-item {
        .el-form-item__content {
          justify-content: center;
          
          .el-input,
          .el-select,
          .el-radio-group,
          .el-textarea {
            width: 400px !important;
          }
        }
      }
    }
  }
}
</style> 